import { defineAsyncComponent } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { createRouter, createWebHashHistory, createWebHistory, RouteRecordRaw } from 'vue-router'
// 引入进度条
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import { useMeanStore } from '../store/menus'
import { useUserStore } from '../store/user'
import { PiniaStore } from '../store/index'
const modules = import.meta.glob("/src/components/**/**.vue");
// 侧边栏菜单数据
import menuList from '../util/router.json'
// import { getList } from '../components/Api/index'
// console.log(createRouter);
const Home = () => import('/src/views/Home.vue')
const Login = () => import('/src/views/Login.vue')
const HomeView = () => import('/src/views/HomeView.vue')
const ErrorPage = () => import('/src/views/ErrorPage.vue')
const routes: Array<RouteRecordRaw> = [
  { path: '/', component: Home, name: 'home' },
  { path: '/login', component: Login, name: 'login' },
  { path: '/HomeView', component: HomeView, name: 'HomeView' },
  { path: '/Error', component: ErrorPage, name: 'ErrorPage' },
  // {
  //   path: "/404",
  //   component: () => import("../views/ErrorPage.vue")
  // },
  {
    path: '/home', name: 'Home', component: Home, meta: { title: '首页' }, children: [
      // 指向设备列表
      {
        path: '/User',
        redirect: '/User/Index',
        name: 'User',
        meta: { title: '用户管理', icon: 'iconfont icon-icon_item_center' },
        children: [
          {
            path: 'Index',
            component: () => import('../components/User/Index.vue'),
            meta: { title: '用户列表' }
          },
        ]
      },
      {
        path: '/Material',
        redirect: '/Material/Index',
        name: 'Material',
        meta: { title: '素材管理', icon: 'iconfont icon-icon_item_center' },
        children: [
          {
            path: 'Index',
            component: () => import('../components/Material/Index.vue'),
            meta: { title: '素材列表' }
          }
        ]
      },
      {
        path: '/Screen',
        redirect: '/Screen/Index',
        name: 'Screen',
        meta: { title: '数据大屏', icon: 'iconfont icon-icon_item_center' },
        children: [
          {
            path: 'Index',
            component: () => import('../components/Screen/Index.vue'),
            meta: { title: '大屏展示' }
          }
        ]
      },
      {
        path: '/SysLog',
        redirect: '/SysLog/Operlog',
        name: 'SysLog',
        meta: { title: '系统管理', icon: 'iconfont icon-icon_item_center' },
        children: [
          {
            path: 'Operlog',
            component: () => import('../components/SysLog/Index.vue'),
            meta: { title: '操作日志' }
          }
        ]
      },
    ]
  },
  // {
  //   path: "/:catchAll(.*)", // 不识别的path自动匹配404
  //   redirect: '/404',
  // },
]

// 3. 创建路由实例并传递 `routes` 配置
// 你可以在这里输入更多的配置，但我们在这里
// 暂时保持简单
const routerHistory = createWebHistory('/');
const router = createRouter({
  // 4. 内部提供了 history 模式的实现。为了简单起见，我们在这里使用 hash 模式。
  history: import.meta.env.MODE === 'development' ? createWebHashHistory() : createWebHashHistory(),
  routes, // `routes: routes` 的缩写
  // 滚动行为，切换页面就置顶
  scrollBehavior(to, from, savedPosition) {
    if (savedPosition) {
      return savedPosition
    } else {
      return { top: 0 }
    }
  }
})
router.beforeEach(async (to, from, next) => {
  NProgress.start()
  const storePinia = PiniaStore()
  storePinia.setRefreshPage()
  let token = sessionStorage.getItem("Token")
  const useMean = useMeanStore()
  const store = useUserStore()
  console.log(to.path)
  if (to.path == '/HomeView') {
    next()
    console.log('大屏页面进来了')
  } else if (to.path == '/login') {
    console.log("login!!!!!!!!!!!")
    next()
  } else if (!token) {
    next({ path: "/login" })
  } else if (to.path == '/' || to.path == '') {
    next({ path: "/" })
  } else if (!useMean.hasRoute) {
    // 获取路由
    // const res: any = await getList()
    let nav = null
    if (store.userInfo.menus_list && store.userInfo.menus_list.length > 0) {
      nav = store.userInfo.menus_list
    } else {
      nav = menuList
    }
    // console.log(nav)
    // const nav = store.userInfo.menus_list
    useMean.setMenuList(nav)
    nav.forEach((menu: { children: any[]; }) => {
      if (menu.children) {
        menu.children.forEach((e: any) => {
          if (!e.component) {
            return
          }
          let route: any = {
            name: e.name,
            path: e.path,
            meta: {
              icon: e.icon,
              keepAlive: e.keepAlive,
              title: e.title
            },
            component: modules[`/src/components${e.component}.vue`]
          }
          router.addRoute("Home", route)
          const err = {
            path: "/:catchAll(.*)",
            name: 'ErrorPage',
            component: () => import('../views/ErrorPage.vue')
          }
          router.addRoute(err)
        })
      }
    })
    useMean.changeRouteStatus(true)
    next({ path: to.path })
    NProgress.done()
  } else {
    console.log("已经有路由了------------")
    next()
  }
})
router.afterEach(async (to, from, next) => {
  // 关闭进度条
  // ElMessage.closeAll();//全局删除Message语句的方法
  // // router.message && router.message.close()
  // setTimeout(() => {
  //   next()
  // }, 500)
  NProgress.done()
})
export default router
